// pages/search/search.js
const wxAjax = require('../../utils/getAjax.js');
const getDate = require('../../utils/util.js');

const createRecycleContext = require('miniprogram-recycle-view')

var listctx = null

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isShow: false,//输入框删除按钮显示控制,true显示
    inputNum: '',//input输入框的初始值,点击删除按钮式设置此值为空
    page: true,//判断重哪个页面过来的，true为主页，false为个人中心页
    reportList: [
      {
        addUserId: "1",
        addUserName: "刘师傅",
        address: "美年广场",
        area: "50",
        checkDate: null,
        city: "成都市",
        createDate: "2020-07-10 14:31:18",
        houseNum: "",
        houseType: "精装",
        id: "edb3b076181344e0bc43a2d9853f8f8c",
        isDelete: 0,
        isSuccess: false,
        name: "测试",
        no: null,
        phone: "18284183388",
        questions: null,
        reportName: "无",
        reportUrl: null,
        signUrl: "",
        sort: null,
        updateDate: null
      }
    ],//报告列表数据
    reportListCache: [],//报告数据列表，请求获取到的数据列表备用。当筛选条件初始化时复制给reportList
    filterType: '1',//1代表电话，2代表楼盘，3代表时间
    filterValue: '',//筛选的条件值
    filterPlaceHolder: '输入电话号码',//筛选输入框的提示
    inputType: 'number',
    maxlength: 11,
    timeStart: '0000-00-00',
    timeEnd: '0000-00-00',
    shuaxinBtnShow: false,  // 刷新按钮的显示，默认不显示
    height: null,
    pageIndex: 1,// 刷新的页码
    reportListlength: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options, '页面传递')
    //如果是从个人中心页面进入的就通过userID查询验房报告列表
    options.page = 'center'
    if (options.page == 'center') {
      this.setData({
        page: false
      })
      wx.setNavigationBarTitle({
        title: '我的验房报告'
      })
      

    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this
    const query = wx.createSelectorQuery()
    query.select('.bottom').boundingClientRect()
    query.selectViewport().boundingClientRect()
    query.select('.report-box .report-item-box').boundingClientRect()
    query.exec(function (res) {
      console.log(res)      // #the-id节点的上边界坐标
      res[1].scrollTop // 显示区域的竖直滚动位置
      that.setData({
        height: res[1].height - res[0].height
      })
      console.log(parseInt(res[2].bottom))
      listctx = createRecycleContext({
        id: 'recycleId',
        dataKey: 'reportList',
        page: that,
        itemSize: {
          width: wx.getSystemInfoSync().screenWidth,
          height: parseInt(res[2].bottom)
        }
      })
      const userId = "b027246d9abf4a399f95382dcb26984a"
      //userId=''时会获取服务器的全部数据，所以为了避免这一情况，需要判断
      if (userId != '') {
        that.userIdSearch({
          userId: userId,
          // startCreateDate: "2021-02-25",
          // endCreateDate: "2021-02-26",
          // phone: "13618092504",
          pageSize: "10",
          pageNumber: that.data.pageIndex
        })
      }
      // ctx.append(that.addlist())
      // ctx.update(beginIndex, list)
      // ctx.destroy()
    })
    
    const time = getDate.formatTime(new Date(), 2)
    this.setData({
      timeEnd: time
    })
  },

  itemSizeFunc: function (item, idx) {
    if (idx < 20) {
      console.log(item, idx)
    }
    return {
      width: 200,
      height: 200
    }
  },

  addlist: function () {
    var list = this.data.reportList
    var data = []
    for (let i = 0; i < 20000; i++) {
      data.push(list[0])
    }

    return data
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (e) {
    console.log(e)
    console.log("显示")
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 输入框输入事件
   */
  searchReport: function (event) {
    // console.log(event.detail.value)
    var _that = this
    const num = event.detail.value
    if (num.length > 0) {
      _that.setData({
        isShow: true
      })
    } else {
      _that.setData({
        isShow: false
      })
    }
    if (num.length === 11) {
      this.search(num)
    } else {
      _that.setData({
        reportList: []
      })
    }

  },

  /**
   * 清空输入框的值
   */
  deleteInput: function () {
    this.setData({
      inputNum: '',
      isShow: false,
      reportList: []
    })
  },

  /**
   * 输入电话号码查询报告 
   * */
  search: function (data) {
    wx.showLoading({
      title: '搜索中...',
    })
    console.log(data)
    var _that = this;
    wxAjax.GET({
      params: { tell: data },
      API_URL: '/web/report/search',
      success: function (res) {
        wx.hideLoading()
        console.log(res, '---------')
        if (res.statusCode === 200) {
          if (res.data.code === 200) {
            _that.setData({
              reportList: res.data.data
            })
          } else {
            _that.showError('获取数据失败')
          }

        } else {
          _that.showError('获取数据失败')
        }
      },
      fail: function (err) {
        wx.hideLoading()
        _that.showError('获取数据失败')
      }
    })
  },

  /** 
   * 
   *通过userId查询报告 
   **/
  userIdSearch: function (params) {
    var pageIndex = params.pageNumber
    var _that = this;
    
    wx.showLoading({
      title: '数据获取中...',
    })
    wxAjax.GET({
      params: params,
      API_URL: '/web/report/pageList',
      success: function (res) {
        console.log(res, '自动')
        wx.hideLoading()
        _that.setData({
          shuaxinBtnShow: false
        })
        if (res.statusCode === 200) {
          if (res.data.code === 200) {
            const now = new Date().getTime()
            res.data.rows.forEach(item => {
              item.chargeType = _that.timeCal(item.createDate, now)
            })

            // _that.setData({
            //   reportList: res.data.data,
            //   reportListCache: res.data.data
            // })
            listctx.append(res.data.rows)
            _that.setData({
              pageIndex: ++pageIndex,
              reportListlength: res.data.total
            })
          } else {
            _that.showError('获取数据失败')
            _that.setData({
              shuaxinBtnShow: true
            })
          }

        } else {
          _that.showError('获取数据失败')
          _that.setData({
            shuaxinBtnShow: true
          })
        }
      },
      fail: function (err) {
        wx.hideLoading()
        _that.showError('获取数据失败')
        _that.setData({
          shuaxinBtnShow: true
        })
      }
    })
  },

  /** 
   * 下载报告文档
  */
  download: function (e) {
    var _that = this;
    wx.showLoading({
      title: '下载中...',
      mask: true
    })
    const id = e.currentTarget.dataset.id
    const name = e.currentTarget.dataset.name
    const baseURL = getApp().url
    const url = baseURL + '/web/report/download?id=' + id
    //rootPath文档保存的本地路径，没有就创建
    const rootPath = wx.env.USER_DATA_PATH + "/houseReportDocument"

    try {
      let fs = wx.getFileSystemManager();
      let result1 = fs.readdirSync(rootPath);
      console.log(result1, "异步")
      //因用户文件限制10M大小，所以清除文件
      fs.rmdirSync(rootPath, true);
    } catch (error) {
      console.log(error, "异步")
    }

    //先创建目录
    mkdir().then(res1 => {
      myDownload()
    }).catch(err => {
      //失败需要取消加载提示框
      wx.hideLoading()
    })

    function myDownload() {
      wx.downloadFile({
        url: url,
        filePath: rootPath + '/' + '验房报告-' + name + '.pdf',
        success(res) {
          wx.hideLoading()
          // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
          if (res.statusCode === 200) {
            // console.log(res, '测试下载')
            const filePath = res.filePath
            wx.openDocument({
              filePath: filePath,
              fileType: 'pdf',
              showMenu: true,
              success: function (res) {
                console.log('打开文档成功')
              },
              fail: function (err) {
                console.log(err, '打不开')
              },
              complete: function () {
                console.log("调用了")
              }
            })
          } else {
            _that.showError('下载失败!！')
          }
        },
        fail: function (err) {
          // console.log(err)
          wx.hideLoading()
          _that.showError('下载失败！')
          //因用户文件限制10M大小，所以下载失败后立即清除文件
          removeReports()
        }
      })
    }

    function mkdir() {
      return new Promise((resolve, reject) => {
        let fs = wx.getFileSystemManager();
        fs.mkdir({
          dirPath: rootPath,
          success: function (res) {
            // console.log(res,'创建成功')
            resolve()
          },
          fail: function (err) {
            // console.log(err,'创建失败')
            reject()
          }
        })
      })
    }

    /**
     * 清理下载的验房报告（本地用户缓存）
     */
    function removeReports() {
      //读取目录文件列表（rootPath目录下存放的是下载的验房报告）
      var fs = wx.getFileSystemManager();

      //读取是否有存放验房报告的目录
      fs.readdir({
        dirPath: rootPath,
        success: function (res) {
          console.log(res, '读取成功')
          //如果有，且有数据，就删除该目录
          if (res.files.length > 0) {
            fs.rmdir({
              dirPath: rootPath,
              recursive: true,
              success: function (res) {
                console.log(res, '删除成功')
              },
              fail: function (err) {
                console.log(err, "删除失败")
              }
            })
          }
        },
        fail: function (err) {
          console.log(err, "读取失败")
        }
      })
    }
  },


  /**
   * 错误提示
  */
  showError: function (msg) {
    wx.showToast({
      title: msg,
      image: '../../img/error.png',
      mask: true,
      duration: 1500,
      success: function () {
        setTimeout(() => {
          wx.hideToast()
        }, 1500)
      }
    })
  },

  /**
   *  复制下载链接
   * */
  copyUrl: function (e) {
    // console.log(e)
    let id = e.currentTarget.dataset.url
    const baseURL = getApp().url
    const url = baseURL + '/web/report/download?id=' + id
    // console.log(url)
    wx.setClipboardData({
      data: url,
      success(res) {
        console.log(res, "成功")
      },
      fail(err) {
        wx.showToast({
          title: '复制失败',
          mask: true,
          icon: 'none',
          duration: 1500,
          success(res) {
            setTimeout(function () {
              wx.hideToast()
            }, 1500)
          }
        })
      }
    })
  },

  /**
   * 备用下载
   */
  standby: function (e) {
    var _that = this;
    wx.showLoading({
      title: '下载中...',
      mask: true
    })
    const id = e.currentTarget.dataset.id
    const baseURL = getApp().url
    const url = baseURL + '/web/report/download?id=' + id
    wx.downloadFile({
      url: url,
      success(res) {
        console.log(res, "备用下载")
        wx.hideLoading()
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        if (res.statusCode === 200) {
          // console.log(res, '测试下载')
          const filePath = res.tempFilePath
          wx.openDocument({
            filePath: filePath,
            fileType: 'pdf',
            showMenu: true,
            success: function (res) {
              console.log('打开文档成功')
            },
            fail: function (err) {
              console.log(err, '打不开')
            },
            complete: function () {
              console.log("调用了")
            }
          })
        } else {
          _that.showError('下载失败!！')
        }
      },
      fail: function (err) {
        // console.log(err)
        wx.hideLoading()
        _that.showError('下载失败！')
      }
    })
  },

  /**
   *  重新编辑
   */
  reEdit: function (e) {
    const that = this
    const id = e.currentTarget.dataset.id
    const chargeType = e.currentTarget.dataset.type
    wx.navigateTo({
      url: '../houseReport/houseReportReEdit/houseReportReEdit?reportId=' + id + '&&chargeType=' + chargeType,
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        // 监听到被打开页面返回数据就说明编辑成功，这个页面更新数据
        acceptDataFromReportEditPage: function (data) {
          console.log(data)
          // 初始化各项值
          that.setData({
            filterPlaceHolder: '输入电话号码',
            inputType: 'number',
            maxlength: 11,
            timeStart: '0000-00-00',
            timeEnd: getDate.formatTime(new Date(), 2),
            filterType: 1,
            filterValue: '',
            reportList: that.data.reportListCache,
            isShow: false
          })
          // 更新报告的数据
          const userId = wx.getStorageSync('userId')
          //userId=''时会获取服务器的全部数据，所以为了避免这一情况，需要判断
          if (userId != '') {
            that.userIdSearch(userId)
          }
        }
      }
    })
  },

  /**
   * 单选框,值改变就清空输入框，并初始化筛选值
   */
  radioChange: function (e) {
    // console.log(e)
    const value = e.detail.value
    const reportListCache = this.data.reportListCache

    if (value == '1') {
      this.setData({
        filterPlaceHolder: '输入电话号码',
        inputType: 'number',
        maxlength: 11,
        timeStart: '0000-00-00',
        timeEnd: getDate.formatTime(new Date(), 2)
      })
    } else if (value == '2') {
      this.setData({
        filterPlaceHolder: '输入楼盘',
        inputType: 'text',
        maxlength: 51,
        timeStart: '0000-00-00',
        timeEnd: getDate.formatTime(new Date(), 2)
      })
    } else if (value == '3') {
      this.setData({
        filterPlaceHolder: '选择时间'
      })
    }

    this.setData({
      filterType: value,
      filterValue: '',
      reportList: reportListCache,
      isShow: false
    })
  },

  /**
   * 清空筛选输入框，并重置数据列表
   */
  deleteFilterInput: function () {
    const reportListCache = this.data.reportListCache
    this.setData({
      filterValue: '',
      isShow: false,
      reportList: reportListCache
    })
  },

  /**
   * 筛选输入框 
   */
  filterReports: function (e) {
    var _that = this
    const value = e.detail.value
    const type = this.data.filterType
    const reportListCache = this.data.reportListCache
    if (value.length > 0) {
      _that.setData({
        isShow: true
      })
    } else {
      _that.setData({
        isShow: false,
        reportList: reportListCache
      })
    }
    if (type == '1') {
      if (value.length > 3) {
        _that.setData({
          reportList: filterArr('phone')
        })
      }
    } else if (type == '2') {
      _that.setData({
        reportList: filterArr('address')
      })
    }

    //当x为phone时，过滤对应的电话。当x为address时，过滤对应的楼盘
    function filterArr(x) {
      const filterList = reportListCache.filter(item => {
        return item[x].indexOf(value) != -1
      })
      return filterList
    }
  },

  /**
   * 开始日期选择器 
   */
  bindDateStartChange: function (e) {
    const that = this
    const dateStart = e.detail.value
    const dateEnd = this.data.timeEnd
    const reportListCache = this.data.reportListCache
    if (!this.comparisonDate(dateStart, dateEnd)) {
      getApp().globalToast("起始日期需小于终止日期", 1000, "none")
      return
    }
    const filterReports = reportListCache.filter(item => {
      const dateArr = item['createDate'].split(' ')
      const compa = that.comparisonDate
      if (compa(dateStart, dateArr[0]) && compa(dateArr[0], dateEnd)) {
        return true
      }
      return false
    })

    this.setData({
      timeStart: dateStart,
      reportList: filterReports
    })
  },

  /**
   * 截止日期选择器 
   */
  bindDateEndChange: function (e) {
    const that = this
    const dateEnd = e.detail.value
    const dateStart = this.data.timeStart
    const reportListCache = this.data.reportListCache
    if (!this.comparisonDate(dateStart, dateEnd)) {
      getApp().globalToast("起始日期需小于终止日期", 1000, "none")
      return
    }
    const filterReports = reportListCache.filter(item => {
      const dateArr = item['createDate'].split(' ')
      const compa = that.comparisonDate
      if (compa(dateStart, dateArr[0]) && compa(dateArr[0], dateEnd)) {
        return true
      }
      return false
    })
    this.setData({
      timeEnd: dateEnd,
      reportList: filterReports
    })
  },

  /* 
   *日期对比,date1<=date2返回true,反之返回false
   */
  comparisonDate: function (date1, date2) {
    const dateArr1 = date1.split('-')
    const dateArr2 = date2.split('-')
    // console.log(dateArr1,dateArr2)
    for (let i = 0; i < dateArr1.length; i++) {
      const x = dateArr1[i]
      const y = dateArr2[i]
      if (i == 0) {
        if (x < y) {
          return true
        } else if (x > y) {
          return false
        }
      } else if (i == 1) {
        if ((x[0] * 10 + x[1]) < (y[0] * 10 + y[1])) {
          return true
        } else if ((x[0] * 10 + x[1]) > (y[0] * 10 + y[1])) {
          return false
        }
      } else if (i == 2) {
        if ((x[0] * 10 + x[1]) <= (y[0] * 10 + y[1])) {
          return true
        } else {
          return false
        }
      }
    }
  },

  /*
  *计算报告生成时间与当前时间差
  */
  timeCal: function (createDate, now = new Date().getTime()) {
    const time = new Date(createDate.replace(/-/g, '/')).getTime()
    const type = (now - time)
    if (type <= 24 * 60 * 60 * 1000) {
      // false免费
      return false
    } else {
      // true 收费
      return true
    }
  },

  /**
   * 刷新获取数据
   */
  refreshReportList: function () {
    const userId = wx.getStorageSync('userId')
    //userId=''时会获取服务器的全部数据，所以为了避免这一情况，需要判断
    if (userId != '') {
      this.userIdSearch(userId)
    }
  },


  /* 触底 */
  bindscrolltolower: function (e) {
    console.log(e)
    var that =this
    const userId = "b027246d9abf4a399f95382dcb26984a"
    //userId=''时会获取服务器的全部数据，所以为了避免这一情况，需要判断
    if (userId != '') {
      this.userIdSearch({
        userId: userId,
        // startCreateDate: "2021-02-25",
        // endCreateDate: "2021-02-26",
        // phone: "13618092504",
        pageNumber: that.data.pageIndex
      })
    }
  }
})
